package com.zbkj.crmeb.system.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.zbkj.crmeb.chant.model.ChannelMerchantAccount;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.enums.BusinessCodeEnum;
import com.zbkj.crmeb.enums.NoticeStatusEnum;
import com.zbkj.crmeb.enums.NoticeTypeEnum;
import com.zbkj.crmeb.enums.SwitchEnum;
import com.zbkj.crmeb.sms.service.SmsService;
import com.zbkj.crmeb.system.dao.MessageConfigDao;
import com.zbkj.crmeb.system.dao.NoticeDao;
import com.zbkj.crmeb.system.model.MessageConfig;
import com.zbkj.crmeb.system.model.Notice;
import com.zbkj.crmeb.system.request.MessageConfigSearchRequest;
import com.zbkj.crmeb.system.request.NoticeSearchRequest;
import com.zbkj.crmeb.system.response.MessageConfigResponse;
import com.zbkj.crmeb.system.response.NoticeResponse;
import com.zbkj.crmeb.system.service.MessageConfigService;
import com.zbkj.crmeb.system.service.NoticeService;
import com.zbkj.crmeb.system.service.SystemAdminService;

@Slf4j
@Service("messageConfigService")
public class MessageConfigServiceImpl extends ServiceImpl<MessageConfigDao, MessageConfig> implements MessageConfigService {
    @Resource
    private MessageConfigDao messageConfigDao;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;

    /**
     * 列表
     * @param request 请求参数
     * @author Mr.Zhang
     * @since 2020-05-27
     * @return List<StoreProduct>
     */
    @Override
    public PageInfo<MessageConfigResponse> getList(MessageConfigSearchRequest request) {
        //条件查询
        Page<MessageConfig> messageConfigPage = PageHelper.startPage(request.getPage(), request.getLimit());
        List<MessageConfigResponse> messageConfigs = messageConfigDao.list(request);
        if(CollectionUtils.isEmpty(messageConfigs)) {
            return CommonPage.copyPageInfo(messageConfigPage, new ArrayList<>());
        }
        return CommonPage.copyPageInfo(messageConfigPage, messageConfigs);
    }

    /**
     * 新增
     *
     * @param messageConfig
     * @return
     */
    @Override
    public boolean addOrUpdate(MessageConfig messageConfig) {
        if (messageConfig.getId() != null) {
            MessageConfig queryObject = this.getById(messageConfig.getId());
            if(messageConfig.getIsOpen() != null){
                queryObject.setIsOpen(messageConfig.getIsOpen());
            }
            if(messageConfig.getFee() != null){
                queryObject.setFee(messageConfig.getFee());
            }
            return this.updateById(queryObject);

        }
        if(messageConfig.getAdminId() == null){
            try {
                int adminId = systemAdminService.getAdminId();
                messageConfig.setAdminId(adminId);
            }catch (Exception e){
                log.error("获取当前用户id报错：{}", e.getMessage());
            }
        }
        if(messageConfig.getBusinessCode() == null) {
            messageConfig.setBusinessCode(BusinessCodeEnum.MERCHANT_ACCOUNT_WARN.getCode());
            messageConfig.setBusinessName(BusinessCodeEnum.MERCHANT_ACCOUNT_WARN.getMsg());
        }else{
            BusinessCodeEnum enumByCode = BusinessCodeEnum.getEnumByCode(messageConfig.getBusinessCode());
            messageConfig.setBusinessName(enumByCode.getMsg());
        }
        if(messageConfig.getIsOpen() == null) {
            messageConfig.setIsOpen(SwitchEnum.OPEN.getCode());
        }
        if(null == messageConfig.getFee()) {
            messageConfig.setFee(new BigDecimal("0.05"));
        }
        messageConfig.setIsDel(SwitchEnum.CLOSE.getCode());

        return this.save(messageConfig);
    }

    /**
     * 发送消息通知和短信提醒
     *
     * @param merId
     * @return
     */
    @Override
    public boolean sendWarningMessage(int merId) {
        log.info("进入sendMessage方法：{}", merId);
        ChannelMerchantAccount channelMerchantAccount = channelMerchantAccountService.getOne(Wrappers.<ChannelMerchantAccount>lambdaQuery().eq(ChannelMerchantAccount :: getMerId, merId));
        log.info("channelMerchantAccount：{}", JSON.toJSONString(channelMerchantAccount));
        // 金额校验
        if(null != channelMerchantAccount.getAccount()) {
            //余额支出 且 余额小于预警金额
            if(channelMerchantAccount.getAccount().compareTo(Constants.FIVE_THOUSAND_BIGDECIMAL)<0){
                MessageConfigSearchRequest request = new MessageConfigSearchRequest();
                request.setMerId(merId);
                request.setBusinessCode(BusinessCodeEnum.MERCHANT_ACCOUNT_WARN.getCode());
                List<MessageConfigResponse> messageConfigs = new ArrayList<>();
                messageConfigs = messageConfigDao.list(request);

                log.info("messageConfigs：{}", JSON.toJSONString(messageConfigs));
                if(CollectionUtils.isNotEmpty(messageConfigs)){
                    MessageConfigResponse configResponse = messageConfigs.get(0);
                    if(null != configResponse && SwitchEnum.OPEN.getCode().equals(configResponse.getIsOpen())) {
                        log.info("sendWarningMessage：{}", JSON.toJSONString(configResponse));
                        smsService.sendWarningMessage(channelMerchantAccount.getMerId(), Constants.FIVE_THOUSAND_BIGDECIMAL);
                        BigDecimal fee = configResponse.getFee();
                        if(null != fee) {
                            BigDecimal newAccount = channelMerchantAccount.getAccount().subtract(fee);
                            if(newAccount.compareTo(BigDecimal.ZERO) >= 0) {
                                channelMerchantAccount.setAccount(newAccount);
                                log.info("new channelMerchantAccount：{}", JSON.toJSONString(channelMerchantAccount));
                                channelMerchantAccountService.updateById(channelMerchantAccount);
                            }
                        }
                    }
                }

                Notice notice = new Notice();
                notice.setMerId(merId);
                log.info("notice：{}", JSON.toJSONString(notice));
                noticeService.add(notice);
                return true;

            }

        }
        return false;
    }

    /**
     * 发送消息通知和短信提醒
     *
     * @param merId
     * @return
     */
    @Override
    public boolean sendMessage(int merId, int businessCode, int templateId, String msg) {

        log.info("进入sendMessage方法：{}", merId);
        MessageConfigSearchRequest request = new MessageConfigSearchRequest();
        request.setMerId(merId);
        request.setBusinessCode(businessCode);
        List<MessageConfigResponse> messageConfigs;
        messageConfigs = messageConfigDao.list(request);

        log.info("messageConfigs：{}", JSON.toJSONString(messageConfigs));
        if(CollectionUtils.isNotEmpty(messageConfigs)){
            MessageConfigResponse configResponse = messageConfigs.get(0);
            if(null != configResponse && SwitchEnum.OPEN.getCode().equals(configResponse.getIsOpen())) {
                log.info("sendWarningMessage：{}", JSON.toJSONString(configResponse));
                smsService.sendMessageV2(merId, templateId, msg);
                BigDecimal fee = configResponse.getFee();
                if(null != fee) {
                    ChannelMerchantAccount channelMerchantAccount = channelMerchantAccountService.getOne(Wrappers.<ChannelMerchantAccount>lambdaQuery().eq(ChannelMerchantAccount :: getMerId, merId));
                    log.info("channelMerchantAccount：{}", JSON.toJSONString(channelMerchantAccount));

                    BigDecimal newAccount = channelMerchantAccount.getAccount().subtract(fee);
                    if(newAccount.compareTo(BigDecimal.ZERO) >= 0) {
                        channelMerchantAccount.setAccount(newAccount);
                        log.info("new channelMerchantAccount：{}", JSON.toJSONString(channelMerchantAccount));
                        channelMerchantAccountService.updateById(channelMerchantAccount);
                    }
                }
            }
        }

        Notice notice = new Notice();
        notice.setMerId(merId);
        notice.setBusinessCode(businessCode);
        notice.setContent(msg);
        log.info("notice：{}", JSON.toJSONString(notice));
        noticeService.add(notice);
        return true;
    }

}